package com.refusea.train.domain.helper

import com.refusea.commons.utils.Sn
import com.refusea.remoting.alibaba.OssApi
import com.refusea.train.domain.ex.BizEx
import com.refusea.train.domain.service.CensorService
import org.springframework.core.env.Environment
import org.springframework.stereotype.Component
import org.springframework.web.multipart.MultipartFile

/**
 * @author Zhang Yan 2024/4/27
 **/
@Component
class UploadHelper(private val censorService: CensorService, environment: Environment) {

    private val dev = environment.activeProfiles.contains("dev")

    private val host = "https://static.refusea.com/"
    private val bucket = "static-refusea"

    fun upload(file: MultipartFile): String {

        val ext = file.originalFilename?.substringAfterLast('.') ?: throw BizEx.of("参数错误")
        val sn = Sn.next16()

        val key = "train/${sn}.${ext}"

        if (OssApi.put(bucket, key, file.bytes, format = ext)) {
            val url = "${host}${key}"
            if (dev || censorService.imageCensor(url)) {
                return url
            } else {
                OssApi.delete(bucket, key)
                throw BizEx.of("图片审核不通过，请勿上传不合规内容")
            }
        } else {
            throw BizEx.of("上传失败")
        }
    }
}
